在 Vue 的 Component 中還有個好用的東西叫做 slot,當開發複雜或巢狀的 component 時,slot 不僅好用更增加了使用上的彈性。
基本上分為三種 slot
<h1>I'm the parent title</h1>
<my-component>
<p>This is some original content</p>
<p>This is some more original content</p>
</my-component>
Vue.component('my-component', {
template:`
<div class="child">
<slot text="hello from child"></slot>
</div>`
})
const vm = new Vue({
el: '#app'
})
附上 fiddle (https://jsfiddle.net/hunterliu/08e5ssrk/)
<my-component>
<h1 slot="header">Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p slot="footer">Here's some contact info</p>
</my-component>
Vue.component('my-component', {
template:`
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>`
})
const vm = new Vue({
el: '#app'
})
附上 fiddle (https://jsfiddle.net/hunterliu/816eckq7/)
範例一:
<app-layout>
<template scope="props">
<span>{{ props.text }}</span>
</template>
</app-layout>
Vue.component('app-layout', {
template: `
<div class="layout">
<h1>我是標題</h1>
<p>我是內容</p>
<slot text="我是app-layout slot"></slot>
</div>
`
});
const vm = new Vue({
el: '#app'
});
附上 codepen (https://codepen.io/hunterliu1003/pen/VypeWm)
範例二:
<list :items="items">
<template slot="item" scope="props">
<li>id: {{props.id}}, text: {{props.text}}</li>
</template>
</list>
Vue.component('list', {
props: ['items'],
template: `
<ul>
<slot name="item" v-for="item in items" :text="item.text" :id="item.id"></slot>
</ul>`
});
const vm = new Vue({
el: '#app',
data: {
items: [
{ id: 1, text: '項目 1' },
{ id: 2, text: '項目 2' },
{ id: 3, text: '項目 3' }
]
}
});
附上 codepen (https://codepen.io/hunterliu1003/pen/QapyqZ)
https://jsfiddle.net/yyx990803/mwLbw11k/?utm_source=website&utm_medium=embed&utm_campaign=mwLbw11k
我一開始也想說怎麼不定義一下slot是啥,不過我發現點進去範例看一看之後就很清楚了~
多謝樓主的撰文~
謝謝~文筆不好請見諒,我會繼續加油